﻿using D.Wx.Dtos;
using D.Wx.Entities;
using FreeSql;

namespace D.Wx.IRepository
{
    public class SysWxUserRepository : ISysWxUserRepository
    {
        private readonly IFreeSql _freeSql;
        public SysWxUserRepository(IFreeSql freeSql)
        {
            _freeSql = freeSql;
        }

        public async Task<int> Add(SysWxUserEntity model)
        {
            return await _freeSql.Insert<SysWxUserEntity>(model).ExecuteAffrowsAsync();
        }

        public async Task<int> Delete(List<string> ids)
        {
            return await _freeSql.Delete<SysWxUserEntity>().Where(m => ids.Contains(m.Id)).ExecuteAffrowsAsync();
        }

        public async Task<SysWxUserEntity> Get(string openId)
        {
            return await _freeSql.Select<SysWxUserEntity>().Where(m=>m.OpenId == openId).FirstAsync();
        }

        public async Task<PageModel<SysWxUserEntityOutput>> QueryPage(SysWxUserEntityQuery pageQuery)
        {
            var sqlQuery = _freeSql.Select<SysWxUserEntity, SysPlatformEntity, SysAdminEntity>()
                                .LeftJoin((m, u, a) => m.SysPlatformUuid == u.UUid)
                                .LeftJoin((m, u, a) => m.SysAdminId == a.Id)
                                .Where((m, u, a) => !m.DeleteFlag)
                                .WhereIf(!string.IsNullOrEmpty(pageQuery.OpenId), (m, u, a) => m.OpenId == pageQuery.OpenId)
                                .WhereIf(!string.IsNullOrEmpty(pageQuery.SysPlatformUuid), (m, u, a) => m.SysPlatformUuid == pageQuery.SysPlatformUuid)
                                .WhereIf(pageQuery.StartTime != null && pageQuery.EndTime != null, (m, u, a) => m.CreateTime.Date >= pageQuery.StartTime.Value.Date && m.CreateTime.Date <= pageQuery.EndTime.Value.Date)
                                .OrderByDescending((m, u, a) => m.CreateTime);

            var totalCount = await sqlQuery.CountAsync();
            var data = await sqlQuery.Page(pageQuery.Current.Value, pageQuery.PageSize.Value).ToListAsync((m, u, a) => new SysWxUserEntityOutput()
            {
                Id = m.Id,
                NickName = m.NickName,
                OrderId = m.OrderId,
                OpenId = m.OpenId,
                SysPlatformUuid = m.SysPlatformUuid,
                SysPlatformName = u.NickName,
                CreateTime = m.CreateTime,
                SysAdminName = a.NickName,
            });
            return new PageModel<SysWxUserEntityOutput>()
            {
                PageNo = pageQuery.Current.Value,
                PageSize = pageQuery.PageSize.Value,
                TotalCount = totalCount,
                TotalPage = (totalCount + pageQuery.PageSize.Value - 1) / pageQuery.PageSize.Value,
                Data = data
            };
        }


    }
}
